Component({
  data: {
    active: null,
    tabs: [],
    role: ''
  },
  attached() {
    this.updateTabsByRole(); // 初始设置
    this.updateActiveByRoute(); // 初始设置 active
  },
  methods: {
    switchTab(e) {
      const index = e.currentTarget.dataset.index;
      const path = this.data.tabs[index].pagePath;
      wx.switchTab({ url: '/' + path });
      this.setData({ active: index });
    },

    // 根据 role 设置 tabs
    updateTabsByRole() {
      const role = wx.getStorageSync('role');
      let tabs = [];
      if (role === 'student') {
        tabs = [
          { pagePath: "pages/homework/selecthomework/selecthomework", text: "学情分析", iconPath: "/static/score.png", selectedIconPath: "/static/score1.png" },
          { pagePath: "pages/homework/userinfo/userinfo", text: "用户信息", iconPath: "/static/userinfo.png", selectedIconPath: "/static/userinfo1.png" }
        ];
      } else if (role === 'teacher') {
        tabs = [
          { pagePath: "pages/homework/homeworkSituation/homeworkSituation", text: "作业情况", iconPath: "/static/score.png", selectedIconPath: "/static/teacherSore.png" },
          { pagePath: "pages/homework/teacherUserinfo/teacherUserinfo", text: "教师信息", iconPath: "/static/userinfo.png", selectedIconPath: "/static/teacherUserinfo.png" }
        ];
      }
      this.setData({ tabs, role });
    },

    // 根据 route 设置高亮
    updateActiveByRoute() {
      const pages = getCurrentPages();
      if (!pages || pages.length === 0) return;
      const currentPage = pages[pages.length - 1].route;
      const tabs = this.data.tabs;
      let active = 0;
      for (let i = 0; i < tabs.length; i++) {
        if (currentPage.includes(tabs[i].pagePath.split('/').pop())) {
          active = i;
          break;
        }
      }
      this.setData({ active });
    },

    // 提供给页面调用：同时刷新 tabs 和 active
    refreshTabBar() {
      this.updateTabsByRole();
      this.updateActiveByRoute();
    }
  }
});
